package net.p2pcdn.pay;

import com.paypal.api.payments.EventType;
import com.paypal.api.payments.Webhook;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import net.p2pcdn.common.PayPalAccessTokenProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WebhookCreator {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private APIContext apiContext;
    @Autowired
    private PayPalAccessTokenProvider payPalAccessTokenProvider;
    @Value("${paypal.mode}")
    private String mode;
    public APIContext getApiContext() {
        return apiContext;
    }

    public void createWebhook() {
        List<EventType> eventTypes = new ArrayList<>();
        EventType eventType1 = new EventType();
        eventType1.setName("PAYMENT.SALE.COMPLETED");
        eventTypes.add(eventType1);
        Webhook webhook = new Webhook();
        webhook.setUrl("http://p2pcdn.net/pay/notify");
        webhook.setEventTypes(eventTypes);
        Webhook createdWebhook = null;
        try {
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", "Basic " + payPalAccessTokenProvider.getAccessToken());
            APIContext context = new APIContext(getApiContext().getClientID(), getApiContext().getClientSecret(), mode);
            context.setHTTPHeaders(header);
            createdWebhook = webhook.create(context, webhook);
            System.out.println("Webhook successfully created with ID " + createdWebhook.getId());
            WebhookConfig.WEB_HOOK_ID = createdWebhook.getId();
        } catch (PayPalRESTException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
